package google.sites.model.commands.attachments;

import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.sites.AttachmentEntry;
import com.google.gdata.data.sites.BasePageEntry;
import com.google.gdata.data.sites.SitesLink;
import com.google.gdata.util.ServiceException;
import dev.tools.design.patterns.command.CommandException;
import google.sites.model.Model;
import google.sites.model.commands.SitesCommand;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 04-10-2013
 * Time: 15:23
 */
public class UploadAttachment extends SitesCommand {

    private File file;
    private String title;
    private String description;
    private String parentLink;

    public UploadAttachment setFile(File file) {
        this.file = file;
        setTitle(file.getName());
        return this;
    }

    public UploadAttachment setTitle(String title) {
        this.title = title;
        return this;
    }

    public UploadAttachment setDescription(String description) {
        this.description = description;
        return this;
    }

    public UploadAttachment setParentLink(String parentLink) {
        this.parentLink = parentLink;
        return this;
    }

    public UploadAttachment setParentPage(BasePageEntry<?> parentPage){
        setParentLink(parentPage.getSelfLink().getHref());
        return this;
    }

    @Override
    protected void protectedExecute() throws CommandException {

        String fileMimeType = Model.INSTANCE.mediaTypes.getContentType(file);

        AttachmentEntry newAttachment = new AttachmentEntry();
        newAttachment.setMediaSource(new MediaFileSource(file, fileMimeType));
        newAttachment.setTitle(new PlainTextConstruct(title));
        newAttachment.setSummary(new PlainTextConstruct(description));
        newAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentLink);

        try {
            setResult(getService().insert(new URL(getContentFeedUrl()), newAttachment));
        } catch (IOException | ServiceException e) {
            throw new CommandException(e);
        }
    }

}
